﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace WebCrawler.HttpConnection
{
    public class HttpSocket
    {
        private Socket _socket;
        private int _timeout = 1000;
        //private NotifyLog _notify;

        private Socket ConnectSocket(string server, int port)
        {
            Socket connectedSocket = null;
            IPHostEntry hostEntry = Dns.GetHostEntry(server);

            foreach (IPAddress address in hostEntry.AddressList)
            {
                IPEndPoint ipe = new IPEndPoint(address, port);
                Socket tmpSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.IP);
                tmpSocket.ReceiveTimeout = _timeout;
                tmpSocket.Connect(ipe);

                if (tmpSocket.Connected)
                {
                    connectedSocket = tmpSocket;
                    break;
                }
            }

            return connectedSocket;
        }

        private void NotifyLog(string log) { }

        private void Open() { }

        //

        public void Close() { }

        /// <summary>
        /// Receive and return Http content from socket connection.
        /// </summary>
        public string Receive(string url)
        {
            string page = "";

            // Create a socket connection with the specified server and port.
            Uri uri = new Uri(url);
            _socket = ConnectSocket(uri.Host, uri.Port);

            if (_socket == null)
                return ("Connection failed");

            // Send request to server.
            string request = "GET /" + uri.PathAndQuery + " HTTP/1.1\r\n Host: " + uri.Host + "\r\nConnection: Close\r\n\r\n";
            Byte[] buffer = Encoding.ASCII.GetBytes(request);
            _socket.Send(buffer, buffer.Length, 0);

            // Content description
            page = "Default HTML page on " + uri.Host + ":\n\r\n";

            // Receive response from server
            buffer = new Byte[_socket.ReceiveBufferSize];
            int bytes = 0;
            do
            {
                bytes = _socket.Receive(buffer, buffer.Length, 0);
                page = page + Encoding.ASCII.GetString(buffer, 0, bytes);
            }
            while (bytes > 0);

            return page;
        }
    }
}
